package com.xjnt.frameworks.plugin.sql.criterion.expression;

import java.io.Serializable;

import com.jfinal.plugin.activerecord.ActiveRecordException;
import com.xjnt.frameworks.plugin.sql.criterion.SqlCriteria;

public class Order implements Serializable{

	private static final long serialVersionUID = 1L;

	private String columnName;
	private boolean ascending;
	
	public static Order asc(String columnName){
		return new Order(columnName, true);
	}
	
	public static Order desc(String columnName){
		return new Order(columnName, false);
	}
	
	protected Order(String columnName, boolean ascending) {
		this.columnName = columnName;
		this.ascending = ascending;
	}
	
	public String toSql(SqlCriteria criteria){
		StringBuilder sql = new StringBuilder();
		if (criteria.isExists(columnName)) {
			sql.append(columnName);
			sql.append(" ");
			sql.append(ascending ? "asc" : "desc");
			return sql.toString();
		} else {
			throw new ActiveRecordException("The "+ columnName + " is not exists ");
		}
	}
}
